﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace MVVM.Models.Services
{
    public class DishService : IDishService
    {
        public List<Dish> GetAllDishes()
        {
            List<Dish> dishList = new List<Dish>();

            string xmlFile = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"data\Data.xml");
            XDocument doc = XDocument.Load(xmlFile);
            var dishes = doc.Descendants("Dish");
            foreach (var item in dishes)
            {
                dishList.Add(new Dish()
                    {
                        Name = item.Element("Name").Value,
                        Category = item.Element("Category").Value,
                        Comment = item.Element("Comment").Value,
                        Score = decimal.Parse(item.Element("Score").Value),
                        Price = double.Parse(item.Element("Price").Value)
                    });
            }

            return dishList;
        }

        public void SetAllDishes(List<Dish> dishes)
        {
            XElement root = new XElement("Dishes");
            foreach (Dish item in dishes)
            {
                root.Add(new XElement("Dish",
                    new XElement("Name", item.Name),
                    new XElement("Category", item.Category),
                    new XElement("Comment", item.Comment),
                    new XElement("Score", item.Score),
                    new XElement("Price", item.Price)
                    ));
            }

            string xmlFile = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"data\Data.xml");
            System.IO.FileStream saveStream = new System.IO.FileStream(xmlFile, System.IO.FileMode.Create,
                 System.IO.FileAccess.Write, System.IO.FileShare.Read);
            root.Save(saveStream);
            saveStream.Close();
        }
    }
}
